﻿using RepositoryAndEf.Core;
using System;
using System.Collections.Generic;
using System.Linq;

namespace RepositoryAndEf.Domain
{
    public class ShoppingCart : BaseEntity
    {
        public ShoppingCart()
        {
            Items = new List<ShoppingCartItem>();
        }

        #region Properties

        public Guid CustomerId { get; set; }
        public virtual User Customer { get; set; }
        public virtual ICollection<ShoppingCartItem> Items { get; set; }

        #endregion

        #region Methods
        public void AddItem(Product product, int quantity)
        {
            // 如果该产品ID已经存在于购物车中，我们直接更改数量即可
            var repetitiveCartItem = Items.FirstOrDefault(
                i => i.ProductId == product.Id);

            if (repetitiveCartItem != null)
            {
                repetitiveCartItem.Quantity += quantity;
                return;
            }

            Items.Add(new ShoppingCartItem
            {
                Product = product,
                ProductId = product.Id,
                Quantity = quantity,
            });
        }
            
        // 更改购物车数量
        public void ChangeProductQuantity(Guid productId, int newQuantity)
        {
            var items = Items as ICollection<ShoppingCartItem>;
            var existingCartItem = items.FirstOrDefault(
                i => i.ProductId == productId);

            if (existingCartItem == null)
            {
                throw new InvalidOperationException(
                    "Cannot find the product in shopping cart");
            }
            existingCartItem.Quantity = newQuantity;
        }

        // 从购物车中移除该产品
        public void RemoveItem(Guid productId)
        {
            var items = Items as ICollection<ShoppingCartItem>;
            var existingCartItem = items.FirstOrDefault(
                i => i.ProductId == productId);

            if (existingCartItem == null)
            {
                throw new InvalidOperationException(
                    "Cannot find the product in shopping cart");
            }

            items.Remove(existingCartItem);
        }
        #endregion
    }
}
